package com.meixiaoliang.portal.core.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.meixiaoliang.portal.modular.system.model.constant.Constant;
import com.meixiaoliang.portal.modular.system.model.response.BasePageResponse;
import com.meixiaoliang.portal.modular.system.model.response.BaseResponse;
import com.meixiaoliang.portal.modular.system.model.response.BaseResultResponse;

/**
 * 数据返回 response 构建工具类
 *
 * @author mei.xiaoliang@qq.com
 */
public class ResponseUtil {

    /**
     * 构建分页
     */
    public static <T> String buildSuccessPageResponse(IPage<T> ipage) {

        BasePageResponse<T> result = new BasePageResponse<T>();
        result.setCode(Constant.SUCCESS_CODE);
        result.setMsg(Constant.SUCCESS_MSG);

        result.setList(ipage.getRecords()); // 分页条数
        result.setPageNum(ipage.getCurrent()); // 当前分页页码
        result.setPageSize(ipage.getSize()); // 当前分页每页条数
        result.setPages(ipage.getPages()); // 总页数
        result.setTotal(ipage.getTotal()); // 总条数

        JSONObject.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm";

        return JSON.toJSONString(result);
    }

    /**
     * 构建成功 response（browse 查询详情）
     */
    public static <T> String buildSuccessResponse(T t) {

        BaseResultResponse<T> result = new BaseResultResponse<T>();
        result.setCode(Constant.SUCCESS_CODE);
        result.setMsg(Constant.SUCCESS_MSG);

        result.setData(t); // 数据

        // 全局时间格式化
        JSONObject.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm";
        String resultString = JSON.toJSONString(result);

        return resultString;

    }

    /**
     * 构建成功 response（add / update / delete post 请求）
     */
    public static String buildSuccessResponse() {

        BaseResponse result = new BaseResponse();
        result.setCode(Constant.SUCCESS_CODE);
        result.setMsg(Constant.SUCCESS_MSG);

        String resultString = JSON.toJSONString(result);
        return resultString;

    }

    /**
     * 用户未登录异常
     */
    public static String buildNotLoginResponse() {

        BaseResponse result = new BaseResponse();
        result.setCode(Constant.NOT_LOGIN_CODE);
        result.setMsg(Constant.NOT_LOGIN_MSG);

        String resultString = JSON.toJSONString(result);
        return resultString;

    }

}
